// 文件上传配置
const multer = require('multer');
const path = require('path');
const fs = require('fs');
require('dotenv').config();

// 确保上传目录存在
const uploadDir = process.env.UPLOAD_PATH || path.join(__dirname, '..', 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 文件存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // 根据上传类型创建子目录
    const type = req.query.type || 'general';
    const typeDir = path.join(uploadDir, type);
    if (!fs.existsSync(typeDir)) {
      fs.mkdirSync(typeDir, { recursive: true });
    }
    cb(null, typeDir);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    const filename = `${path.basename(file.originalname, ext)}-${uniqueSuffix}${ext}`;
    cb(null, filename);
  }
});

// 文件过滤
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedTypes = /jpeg|jpg|png|gif|pdf|doc|docx|txt/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);

  if (extname && mimetype) {
    return cb(null, true);
  } else {
    cb(new Error('只允许上传图片、PDF、文档和文本文件'));
  }
};

// 创建上传实例
const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 10485760, // 10MB
    files: 5 // 最多5个文件
  }
});

/**
 * 处理单个文件上传
 * @param {string} fieldName - 表单字段名
 * @returns {Function} - multer中间件
 */
const singleFileUpload = (fieldName = 'file') => {
  return upload.single(fieldName);
};

/**
 * 处理多个文件上传
 * @param {string} fieldName - 表单字段名
 * @param {number} maxCount - 最大文件数量
 * @returns {Function} - multer中间件
 */
const multipleFilesUpload = (fieldName = 'files', maxCount = 5) => {
  return upload.array(fieldName, maxCount);
};

module.exports = {
  upload,
  singleFileUpload,
  multipleFilesUpload,
  uploadDir
};